package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class TestA_01 {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        //读取绝对路径的文件
//        Document doc = db.parse("D:\\a.xml");
        //读取相对路径(运行目录)的文件
//        String path = TestA.class.getClassLoader().getResource("a.xml").getPath();
//        System.out.println(path);
        //解析XML文档，得到一个Document对象
        Document doc = db.parse(TestA_01.class.getClassLoader().getResourceAsStream("a.xml"));
        //直接命中stu节点
        NodeList nodeList = doc.getElementsByTagName("stu");
        for(int i = 0; i < nodeList.getLength(); i++){
            Node node = nodeList.item(i);
            Element element = (Element) node;
            System.out.println(element.getAttribute("name")+
                    "\t"+element.getAttribute("age")+
                    "\t"+element.getAttribute("gender"));
        }
    }
}
